package abacab.router;

import abacab.router.KeyAwareRouter.KeyExtractor;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;
import com.typesafe.config.ConfigException.BadValue;

/**
 * The factory handling the creation of the "key aware" router
 * 
 * @param <M>
 *          the type of message
 */
public class KeyAwareRouterFactory<M> implements RouterFactory<M> {
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Router<M> buildRouter(Config config) throws ConfigException {
		// Get the extractor
		String extractorImpl = config.getString("extractor");
		Class<KeyExtractor> extractorClass;
		try {
			extractorClass = (Class<KeyExtractor>) Class.forName(extractorImpl);
		}
		catch (ClassNotFoundException e) {
			throw new BadValue("extractor", "The key-aware router's extractor implementation \"" + extractorImpl
					+ "\" does not exist", e);
		}
		catch (ClassCastException e) {
			throw new BadValue("extractor", "The key-aware router's extractor implementation \"" + extractorImpl
					+ "\" does not implement \"" + KeyExtractor.class.getName() + "\"");
		}

		// Build the extractor
		KeyExtractor extractor;
		try {
			extractor = extractorClass.newInstance();
		}
		catch (Exception e) {
			throw new BadValue("extractor", "The key-aware router's extractor implementation \"" + extractorImpl
					+ "\" can not be built", e);
		}
		return new KeyAwareRouter(extractor);
	}
}